package org.xue.snowmall.bargain.service.impl;

import entity.UserRecordEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.xue.snowmall.bargain.entity.BargainEntity;
import org.xue.snowmall.bargain.service.BargainService;
import org.xue.snowmall.common.utils.PageUtils;
import org.xue.snowmall.common.utils.Query;

import org.xue.snowmall.bargain.dao.BargainRecordDao;
import org.xue.snowmall.bargain.entity.BargainRecordEntity;
import org.xue.snowmall.bargain.service.BargainRecordService;
import org.xue.snowmall.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Service("bargainRecordService")
public class BargainRecordServiceImpl extends ServiceImpl<BargainRecordDao, BargainRecordEntity> implements BargainRecordService {

    @Autowired
    private BargainService bargainService;

    @Autowired
    private HttpSession session;

    @Autowired
    private HttpServletRequest request;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BargainRecordEntity> wrapper = new QueryWrapper<>();
        UserRecordEntity user = (UserRecordEntity) request.getSession().getAttribute("user");
        wrapper.eq("usm_id",user.getUsmId());
        IPage<BargainRecordEntity> page = this.page(
                new Query<BargainRecordEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public R saveBargainRecord(Long gsmBargainId) {

        BargainRecordEntity bargainRecordEntity = new BargainRecordEntity();
        //根据活动id查出活动相应的数据
        BargainEntity bargainEntity = bargainService.getById(gsmBargainId);
        BeanUtils.copyProperties(bargainEntity, bargainRecordEntity);
        bargainRecordEntity.setGsmCreateTime(new Date());
        bargainRecordEntity.setGsmBargainCountNow(0);
        bargainRecordEntity.setGsmBargainPriceNow(bargainEntity.getPsmPrice());
        bargainRecordEntity.setGsmBargainRecordStatus("0");
        //获取当前用户id
        UserRecordEntity user = (UserRecordEntity) session.getAttribute("user");
        if (user == null) {
            return R.error();
        }
        bargainRecordEntity.setUsmId(user.getUsmId());
        bargainRecordEntity.setUsmName(user.getUsmName());
        //用户生成的推广码 就是传递用户信息以及当前
        baseMapper.insert(bargainRecordEntity);
        bargainRecordEntity.setGsmBargainCode("http://bargain.snow-mall.com/saveHelpRecord?gsmBargainRecordId="+bargainRecordEntity.getGsmBargainRecordId());
        baseMapper.updateById(bargainRecordEntity);
        return R.ok();
    }

}